package org.stratusdb;

import java.io.*;
import java.net.*;

import org.stratusdb.types.AbstractType;
import org.stratusdb.types.SQLInteger;
import org.stratusdb.types.SQLVarchar;
import org.stratusdb.types.TableType;
import org.stratusdb.types.TupleType;

public class Client {
	public static void main(String[] args) {
	    Socket t = null;
	    try
	    {
	      int i = 0;
	      t = new Socket("localhost",Config.PORT);
	      PrintStream os = new PrintStream( t.getOutputStream() );
	      BufferedReader in = new BufferedReader(
                  new InputStreamReader( System.in ) );
	      while(true) {
	    	  String s = in.readLine();
	    	  os.println(s);
	    	  os.flush();
	    	  ObjectInputStream server = new ObjectInputStream(t.getInputStream());
	    	  Object answer = server.readObject();
	    	  if(answer instanceof org.stratusdb.error.Error) {
	    		  i=0;
	    		  System.out.println(((org.stratusdb.error.Error)answer).toString());
	    	  }
	    	  if(answer instanceof TableType) {
    			for(TupleType tt : ((TableType)answer).getTuples()) {
    				StringBuilder erg = new StringBuilder();
    				if(tt==null) break;
    				System.out.println("Tuple "+ ++i);
    				for(AbstractType at : tt.getValues()){
    					if(at==null) break;
    					if(at instanceof SQLVarchar) erg.append(((SQLVarchar)at).getValue()+ "\t");
    					if(at instanceof SQLInteger) erg.append(((SQLInteger)at).getValue()+ "\t");
    				}
    				System.out.println(erg);
    			}
	    	  }
	    	  
	    	  if(answer == null) System.out.println("No more data available.");
	      }
	    }
	    catch (Exception e ) {
	      e.printStackTrace();
	    }
	    finally
	    {
	      if ( t != null )
	        try { t.close(); } catch ( IOException e ) { e.printStackTrace(); }
	    }
	}
}
